import 'dart:io';

import 'package:enjoy_plus_flutter_7/eventBus/event_bus.dart';
import 'package:enjoy_plus_flutter_7/utils/PhotoDilage.dart';
import 'package:enjoy_plus_flutter_7/utils/toast.dart';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

import '../../api/login.dart';

class ProfilePage extends StatefulWidget {
  const ProfilePage({super.key, required this.userInfo});
  final Map<String, dynamic> userInfo;
  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  TextEditingController controller = TextEditingController();
  bool _isUpload = false; //是否上传中
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    controller.text = widget.userInfo['nickName'];
  }

  Widget getAvatar() {
    if (widget.userInfo['avatar'] != null && widget.userInfo['avatar'] != '') {
      if (widget.userInfo['avatar'].startsWith('/data')) {
        return Image.file(
          File(widget.userInfo['avatar']),
          width: 30,
          height: 30,
        );
      }
      return Image.network(
        widget.userInfo['avatar'],
        width: 30,
        height: 30,
      );
    } else {
      Image.asset(
        'assets/images/avatar_1.jpg',
        width: 30,
        height: 30,
      );
    }

    return widget.userInfo['avatar'] != null && widget.userInfo['avatar'] != ''
        ? Image.network(
            widget.userInfo['avatar'],
            width: 30,
            height: 30,
          )
        : Image.asset(
            'assets/images/avatar_1.jpg',
            width: 30,
            height: 30,
          );
  }

  _selectPhoto() async {
    ImagePicker imagePicker = ImagePicker();
    XFile? file = await imagePicker.pickImage(source: ImageSource.gallery);
    if (file != null) {
      // if (kIsWeb) {
      if (_isUpload) return;
      _isUpload = true;
      var res = await uploadImgApi(file);

      widget.userInfo['avatar'] = res['url'];
      setState(() {});
      Navigator.pop(context);
      PromptAction.success('上传成功');
      event_bus.fire(LogSccessEvent());
      _isUpload = false;
      // }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('个人信息'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: ListView(
        padding: const EdgeInsets.all(10),
        children: [
          SizedBox(
            height: 40,
            child: Row(
              children: [
                const Text(
                  '头像',
                  style: TextStyle(fontSize: 16),
                ),
                const Spacer(),
                Row(
                  children: [
                    GestureDetector(
                      onTap: () {
                        showPhotoDialog(context, () {
                          _selectPhoto();
                        });
                      },
                      child: ClipRRect(
                          borderRadius: BorderRadius.circular(50.0),
                          child: getAvatar()),
                    ),
                    const Icon(Icons.arrow_forward_ios, size: 12)
                  ],
                )
              ],
            ),
          ),
          Row(
            children: [
              const Text('昵称'),
              const Spacer(),
              Expanded(
                child: TextField(
                  controller: controller,
                  decoration: const InputDecoration(
                    hintText: '请输入昵称',
                    border: InputBorder.none,
                  ),
                  textAlign: TextAlign.right,
                ),
              ),
              const Icon(Icons.arrow_forward_ios, size: 12)
            ],
          ),
          const SizedBox(
            height: 20,
          ),
          Row(
            children: [
              Expanded(
                child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color.fromARGB(255, 85, 145, 175),
                    minimumSize: const Size(100, 50),
                  ),
                  onPressed: () async {
                    await updateUserApi({
                      'nickName': controller.text,
                      // 'avatar': widget.userInfo['avatar']
                    });

                    PromptAction.success('保存成功');
                    event_bus.fire(LogSccessEvent());
                  },
                  child: const Text(
                    '保存',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 20,
                    ),
                  ),
                ),
              )
            ],
          )
        ],
      ),
    );
  }
}
